/**
 * The MIT License (MIT)
 * 
 * Copyright (c) 2016 mo_yq5 (mo_yq5@163.com)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 */
package com.vulgarsdk.captcha;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 验证码配置项操作类
 * @author mo_yq5
 * @since 2016年1月10日
 */
public abstract class CaptchaSettingAbstract implements CaptchaSetting {

	private static Logger log = LoggerFactory.getLogger(CaptchaSettingAbstract.class);
	/**
	 * classpath路径下的配置文件
	 */
	private static String config;
	/**
	 * 配置信息
	 */
    private static Properties preperties;
    
    /**
     * 重新加载配置文件，并初始化配置项。
     * 通过setConfig(String)方法自定义配置文件路径，
     * 如果不指定，则默认加载类目录下的captcha.properties文件。
     * @see #setConfig(String)
     */
    public static void reset() {
        preperties = new Properties();
        try {
        	if (null == config) {
        		config = CaptchaSettingAbstract.class.getPackage().getName().replaceAll("\\.", "/") + "/captcha.properties";
        	}
        	preperties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(config));
        } catch (Exception e) {
            log.error("验证码配置项初始化异常：", e);
        }
    }
    
    /**
     * 获取配置项
     * @param key
     * @return value
     */
    public String getProperty(String key) {
    	if (null == preperties) {
    		reset();
    	}
        return String.valueOf(preperties.get(key));
    }

	/**
	 * 获取当前配置文件名
	 * @return the config
	 */
	public static String getConfig() {
		return config;
	}

	/**
	 * 指定配置文件名，该文件名必须是classpath路径的，调用此方法后，必须调用<code>reset()</code>方法新的配置才能生效
	 * @param config 文件名
	 * @see #reset()
	 */
	public static void setConfig(String config) {
		CaptchaSettingAbstract.config = config;
	}

	/**
	 * 获取配置项集合
	 * @return the preperties
	 */
	public static Properties getPreperties() {
		return preperties;
	}

	/**
	 * 指定配置项信息，此方法直接覆盖原配，直接使用指定的配置信息
	 * @param preperties
	 */
	public static void setPreperties(Properties preperties) {
		CaptchaSettingAbstract.preperties = preperties;
	}

}
